package com.yanqu.road.dataHelper.action.excel;

import com.yanqu.road.dataHelper.gameServer.GameServer;
import com.yanqu.road.dataHelper.manager.DataMgr;
import com.yanqu.road.dataHelper.repair.BaseRepair;
import com.yanqu.road.entity.player.UserVehicle;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import sun.misc.OSEnvironment;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author xx
 * @Date 2020/11/11
 */
public class ZhuanyuanBug extends BaseRepair {

    public ZhuanyuanBug(GameServer gameServer) {
        super(gameServer);
    }

    @Override
    public void repair(long param1, String param2) {

    }

    public void go1() {
        try {
            String activityIdStr = "9068059,9068060,9068061,9068062,9068063,9068064,9068065,9068066,9068067,9068068,9068069,9068070,9068071,9068072,9068073,9068074,9068075,9068076,9068077,9068078,9068079,9068080,9068081,9068082,9068083,9068084,9068085,9068086,9068087,9068088,9068089,9068090,9068091,9068092,9068093,9068094,9068095,9068096,9068097,9068098,9068099,9068100,9068101,9068102,9068103,9068104,9068105,9068151,9068152,9068153,9068154,9068155,9068156,9068157,9068235,9068236,9068237,9068238,9068239,9068240,9068241,9068242,9068243,9068244,9068245,9068246,9068247,9068248,9068249,9068250,9068251,9068252,9068253,9068254,9068255,9068256";
            List<Map<String, String>> listMap = new ArrayList<>();
            listMap = getLog(activityIdStr);


            //回收道具
            for (Map<String, String> map : listMap) {
                String serverId = map.get("serverId");
                String userId = map.get("userId");
                if (Objects.equals(userId, "201000010012220")) {
                    continue;
                }
                String rewardStr = map.get("reward");
                String time = map.get("time");
                Property reward = PropertyHelper.parseStringToProperty(rewardStr);
                for (Map.Entry<Integer, BigInteger> entry : reward.getGoods().entrySet()) {
                    Integer goodsId = entry.getKey();
                    BigInteger num = entry.getValue();
                    if (isVehicleGoods(goodsId)) {
                        //珍兽
                        removeVehicle(userId, goodsId, num,time);
                    } else if (isDecorationGoods(goodsId)) {
                        //回收装饰
                        removeDecoration(userId, goodsId, num);
                    } else if (isBanquet(goodsId)) {
                        //回收宴会帖
                        removeBanquet(userId, goodsId, num,time);
                    } else {
                        //回收道具
                        removeBagItem(userId, goodsId, num);
                    }

                }
            }
            DataMgr.addData(listMap);

        } catch (Exception e) {
            getLogger().error(e);
        }
    }

    private void removeVehicle(String userId, Integer goodsId, BigInteger num, String time) throws Exception{
        UserVehicle vehicle = getVehicle(userId, goodsId, DateHelper.getString2Date(time).getTime() - 5000);
        if (vehicle == null) {
            //找不到 卧槽
            getLogger().error("========  can't find userId: {}, vehicle: {}", userId, goodsId);
        } else if (vehicle.isDelete()) {
            getLogger().error("======== userId: {}, vehicle delete.  {}", userId, vehicle.getVehicleUid());
        }else {
            String getSql = "update  t_u_vehicle set isDelete = 1 where userId=? and vehicleUid = ?";
            PreparedStatement ps = getGameServer().getConnection().prepareStatement(getSql);
            int i = 1;
            ps.setLong(i++, Long.parseLong(userId));
            ps.setString(i++, vehicle.getVehicleUid());
            ps.executeUpdate();
            getGameServer().closeConnection(ps, null);
            getLogger().error("========    userId: {}, vehicle delete.  {}", userId, vehicle.getVehicleUid());
        }
    }

    private void removeDecoration(String userId, Integer goodsId, BigInteger num)throws Exception {
        long reduceTime = num.intValue() * 15L * 24 * 3600;
        updateDecoration(userId, goodsId, reduceTime);
    }

    private void removeBanquet(String userId, Integer goodsId, BigInteger num, String time)throws Exception {
        int type = 0;
        if (goodsId == 110099) {
            type = 4;
        }else
        if (goodsId == 110100) {
            type = 5;
        }else
        if (goodsId == 110101) {
            type = 6;
        }

        String id = getBanquet(userId, type, DateHelper.getString2Date(time).getTime() - 5000);
        if (id == null) {
            getLogger().info("========  userId: {}, goodsId: {}, num: {}", userId, goodsId, -1);
        }else {
            String getSql = "update  t_u_banquet_invitation set isUsed = ? where userId=? and iId = ?";
            PreparedStatement ps = getGameServer().getConnection().prepareStatement(getSql);
            int i = 1;
            ps.setInt(i++, 3);
            ps.setLong(i++, Long.parseLong(userId));
            ps.setString(i++, id);
            ps.executeUpdate();
            getGameServer().closeConnection(ps, null);
            getLogger().info("========  userId: {}, banquetId: {}", userId, id);
        }
    }

    private void removeBagItem(String userId, Integer goodsId, BigInteger num)throws Exception {
        int hasNum = getGoodsNum(userId, goodsId);

        int lastNum = hasNum - num.intValue();
        int modifyNum = 0;
        if (lastNum >= 0) {
            //扣除
            modifyNum = lastNum;
        }else {
            getLogger().info("========  userId: {}, goodsId: {}, num: {}", userId, goodsId, lastNum);
        }
        String getSql = "update  t_u_bag set num = ? where userId=? and goodsId = ?";
        PreparedStatement ps = getGameServer().getConnection().prepareStatement(getSql);
        int i = 1;
        ps.setInt(i++, modifyNum);
        ps.setLong(i++, Long.parseLong(userId));
        ps.setInt(i++, goodsId);
        ps.executeUpdate();
        getGameServer().closeConnection(ps, null);
        getLogger().info("========  userId: {}, goodsId: {}, hasNum: {} ,removeNum: {}", userId, goodsId, hasNum,num.intValue());
    }

    private void   updateDecoration(String userId, int goodsId,long reduceTime) throws SQLException {
        String getSql = "update  t_u_decoration set endTime = endTime  - ? where userId=? and decorationId = ?";
        PreparedStatement ps = getGameServer().getConnection().prepareStatement(getSql);
        int i = 1;
        ps.setLong(i++, reduceTime);
        ps.setLong(i++, Long.parseLong(userId));
        ps.setInt(i++, goodsId);
        ps.executeUpdate();
        getGameServer().closeConnection(ps, null);
    }

    private String  getBanquet(String userId, int type,long time) throws SQLException {
        String getSql = "select * from t_u_banquet_invitation where userId=? and type = ? and createTime >= ? and isUsed = 0";
        PreparedStatement ps = getGameServer().getConnection().prepareStatement(getSql);
        int i = 1;
        ps.setLong(i++, Long.parseLong(userId));
        ps.setInt(i++, type);
        ps.setLong(i++, time);
        ResultSet rs = ps.executeQuery();
        int num = 0;
        if (rs.next()) {
            return rs.getString("iId");
        }
        getGameServer().closeConnection(ps, rs);
        return null;
    }

    private UserVehicle  getVehicle(String userId, int goodsId,long time) throws SQLException {
        String getSql = "select * from t_u_vehicle where userId=? and templateId = ? and createTime >= ? ";
        PreparedStatement ps = getGameServer().getConnection().prepareStatement(getSql);
        int i = 1;
        ps.setLong(i++, Long.parseLong(userId));
        ps.setInt(i++, goodsId);
        ps.setLong(i++, time/1000);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            UserVehicle data = new UserVehicle();
            data.setVehicleUid(rs.getString("vehicleUid"));
            data.setUserId(rs.getLong("userId"));
            data.setTemplateId(rs.getInt("templateId"));
            data.setPatronsId(rs.getInt("patronsId"));
            data.setLevel(rs.getInt("level"));
            data.setBreakLv(rs.getInt("breakLv"));
            data.setStudyLv(rs.getInt("studyLv"));
            data.setEquipTimes(rs.getInt("equipTimes"));
            data.setEquipBuyTimes(rs.getInt("equipBuyTimes"));
            data.setCreateTime(rs.getLong("createTime"));
            data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
            data.setDelete(rs.getBoolean("isDelete"));
            return data;
        }
        getGameServer().closeConnection(ps, rs);
        return null;
    }



    private int getGoodsNum(String userId, Integer goodsId) throws SQLException {
        String getSql = "select * from t_u_bag where userId=? and goodsId = ?";
        PreparedStatement ps = getGameServer().getConnection().prepareStatement(getSql);
        int i = 1;
        ps.setLong(i++, Long.parseLong(userId));
        ps.setInt(i++, goodsId);
        ResultSet rs = ps.executeQuery();
        int num = 0;
        if (rs.next()) {
            num = rs.getInt("num");
        }
        getGameServer().closeConnection(ps, rs);
        return num;
    }

    public static boolean isBanquet(int goodsId) {
        return 110099 == goodsId || 110100 == goodsId || 110101 == goodsId;
    }


    public static boolean isVehicleGoods(int goodsId) {
        return goodsId >= 104000 && goodsId <= 104999;
    }

    public static boolean isDecorationGoods(int goodsId) {
        return goodsId >= 106000 && goodsId <= 106999;
    }

    private List<Map<String, String>> getLog(String activityIdStr) {
        List<Map<String, String>> dataList = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,reward,`time` " +
                " from t_l_activity_reward WHERE activityId in(" + activityIdStr + ") and conditionId = 1000101";
        // and shopType in(109,)
        try {
            call = getGameServer().getLogConnection().prepareCall(sql);
            int i = 1;
            rs = call.executeQuery();
            while (rs.next()) {
                Map<String, String> temp = new ConcurrentHashMap<>();
                temp.put("serverId", String.valueOf(getGameServer().getServerInfo().getServerId()));
                temp.put("userId", checkNullToEmpty(rs.getString("userId")));
                temp.put("reward", checkNullToEmpty(rs.getString("reward")));
                temp.put("time", checkNullToEmpty(rs.getString("time")));
                dataList.add(temp);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return dataList;
    }


}
